﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using Scoreboard.Model;

namespace Scoreboard.Providers
{
	public class ScoreboardRoleProvider : RoleProvider 
	{
		private string _applicationName;

		public override void AddUsersToRoles(string[] usernames, string[] roleNames)
		{
			throw new NotImplementedException();
		}

		public override string ApplicationName
		{
			get
			{
				return _applicationName;
			}
			set
			{
				_applicationName = value;
			}
		}

		public override void CreateRole(string roleName)
		{
			var container = new EntitiesContainer();
			
			var role = new Role
			{
				Name = roleName
			};
			
			container.AddToRoles(role);
			container.SaveChanges();			
		}

		public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
		{
			var container = new EntitiesContainer();

			var role = container.Roles.Where(r => r.Name == roleName).FirstOrDefault();
			if (role == null)
			{
				return false;
			}
			container.Roles.DeleteObject(role);
			container.SaveChanges();
			return true;
		}

		public override string[] FindUsersInRole(string roleName, string usernameToMatch)
		{
			throw new NotImplementedException();
		}

		public override string[] GetAllRoles()
		{
			var container = new EntitiesContainer();

			return container.Roles.Select(r => r.Name).ToArray<string>();			
		}

		public override string[] GetRolesForUser(string username)
		{
			var container = new EntitiesContainer();

			var user = container.Users.Where(u => u.Login == username).FirstOrDefault();
			if (user != null)
			{
				return user.Roles.Select(r => r.Name).ToArray<string>();
			}

			return new string[0];
		}

		public override string[] GetUsersInRole(string roleName)
		{
			throw new NotImplementedException();
		}

		public override bool IsUserInRole(string username, string roleName)
		{
			var container = new EntitiesContainer();

			var user = container.Users.Where(u => u.Login == username).FirstOrDefault();
			var result = user.Roles.Where(r => r.Name == roleName).Count() > 0;

			return result;
		}

		public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
		{
			throw new NotImplementedException();
		}

		public override bool RoleExists(string roleName)
		{
			var container = new EntitiesContainer();

			var result = container.Roles.Where(r => r.Name == roleName).Count() > 0;

			return result;
		}
	}
}
